package com.ayf.payment.game.api.task.ayb;

import com.ayf.payment.game.api.service.MerchantPayOrderService;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import com.swwx.charm.zookeeper.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * task定时任务清单
 * @author lch
 * @date 2021/11/4
 */
@Component
@Async
@Slf4j
public class AySchedulingJobs {

    @Resource
    private DistributedLock distributedLock;

    @Resource
    private MerchantPayOrderService merchantPayOrderService;

    /**
     * 爱游宝代付定时刷任务状态
     * @author lch
     * @date 2021/12/10
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void merchantPayOrderServiceRefreshTask() {
        boolean lock = false;
        String traceId = SnowFlakeUtils.getTraceId();
        String lockName = "爱游宝代付定时刷任务状态".concat(System.getenv("XY_GAME_PAY_LOCK_FLAG"));
        try {
            if (lock = distributedLock.getLock(lockName)) {
                this.merchantPayOrderService.refresh();
            }
        } catch (GetLockFailedException e) {
            LogPortal.error("{} >>> [DISTRIBUTED_LOCK_ACQUIRE_FAILED_ZK] 分布式锁获取失败,锁名称为:{}", e, traceId, lockName);
        } catch (Exception e) {
            LogPortal.error("{} >>> {} 任务执行出错 ", e, traceId, lockName);
        } finally {
            if (lock) {
                LogPortal.info(traceId + " >>> " + lockName + " finished.");
                try {
                    distributedLock.releaseLock(lockName);
                } catch (ReleaseLockFailedException e) {
                    LogPortal.error("{} >>> [DISTRIBUTED_LOCK_RELEASE_FAILED_ZK] 分布式锁释放失败,锁名称为:{}", e, traceId, lockName);
                }
            }
        }
    }
}
